<?php
namespace App\Repos;

use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\OrderProcess;
use App\Models\OrderPoint;
use App\Models\OrderRefund;
use App\Models\OrderComment;
use App\Models\Product;

use App\Services\RedisService;
use App\Services\WechatTpl;
use EasyWeChat;
use function EasyWeChat\Kernel\Support\generate_sign;
use DB;
use Log;
use Carbon\Carbon;

class OrderRepo
{
	// 后台订单分页
	public static function  paginate($where=[],$num=6,$orderBy='id',$orderWay='desc')
	{

		$query = Order::query();
		if(array_get($where,'cate_id')) {
			$cate_id = array_pull($where,'cate_id');
			$product_ids = Product::where(['cate_id'=>$cate_id])
									->pluck('id');
			$order_ids = OrderProduct::whereIn('product_id',$product_ids)->pluck('order_id');	
			$query->whereIn('id',$order_ids);						
		}
		$list = $query->where($where)
					->where('status','!=','1')
	  				->with('products','address','user','userCoupon')
	  				->orderBy($orderBy,$orderWay)
	  				->paginate($num); 
	  	return $list;  
	}

	

	// 用户端订单分页
	public static function  pages($where=[],$num=5,$orderBy='id',$orderWay='desc')
	{	   
		$query = Order::query();
		$status = array_pull($where,'status');
		
			
			if($status==2) {
				$query->whereIn('status',['2','3']);
			}elseif($status==3) {
				$query->whereIn('status',['4']);
			}elseif($status==100){
				$query->whereIn('status',['100']);
			}else{
				$query->whereIn('status',['2','3','4','100']);
			}
		
		$list = $query->with(['products'])
				->where($where)
				->orderBy($orderBy,$orderWay)
	  			->paginate($num); 
	  				
	  	return $list;     
	}

	public static function find($where)
	{		
		$order = Order::where($where)->with('products','address')->first();
		return $order;
	}

	/**
	 * 创建订单
	 */
	public static function create($data,$products=[])
	{
		$openid        = array_pull($data,'openid');
		$total_money   = (int)$data['total_money'];		

		DB::beginTransaction();
		try {
			// 用了满减券 那么券就废了
			if(array_key_exists('user_coupon_id', $data)) {
				UserCouponRepo::update(['id'=>$data['user_coupon_id']],['is_used'=>1]);					
			}

			// 用了代金券 那么券就废了
			if(array_get($data,'user_voucher_id')) {
				UserVoucherRepo::update(['id'=>$data['user_voucher_id']],['is_used'=>1]);
				$uv = UserVoucherRepo::find(['id'=>$data['user_voucher_id']]);		
				$data['voucher_info'] = $uv->voucher_value/100	;		
			}

			$order    = Order::create($data);
			
			if($products) {
				foreach ($products as $key => $v) {
					
					$v['order_id'] = $order->id;
					$v['shop_id']  = $data['shop_id'];
					OrderProduct::create($v); 
					// 是放购物车
					$cartWhere['user_id']    = $data['user_id'];					
					$cartWhere['shop_id']    = $data['shop_id'];
					$cartWhere['product_id'] = $v['product_id'];
					CartRepo::release($cartWhere);
				}	
			}

			// 如果用了余额要剪掉
			$moneyLog = array_only($data,['user_id','shop_id']);
			$moneyLog['type']  = 2;
			$moneyLog['money'] = $data['user_money'];
			$moneyLog['order_id'] = $order->id;
			//dd($moneyLog);
			$rs = UserMoneyLogRepo::create($moneyLog);
			if($rs['status'] = false) {
				DB::rollBack();
			}

			DB::commit();
		} catch (\Exception $e) {
			dd($e->getMessage());			
			DB::rollBack();
			return false;
		}

		
		

		$unifyData['openid']       = $openid;
		$unifyData['total_money']  = $total_money;
		$unifyData['code']         = $data['code'];
		$unifyData['order_id']     = $order->id;
		return self::wechatUnifyOrder($unifyData);
	}

	


	/**
	 * 确认订单
	 */
	public static function confirm($data)
	{
		$rs['status'] = false;
		$rs['msg']    = '操作失败';
		$order_status = 3;
		
		//先检查订单的状态防止误操作 订单状态在待付款1或者已付款2的才可以确认
		// 因为现在没有线上付款 所以直接改为3
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);

			if($order->status>2||$order->status<1) {
				$rs['msg'] = '订单状态错误';
				return $rs;
			}
			
			
			$order->status = $order_status;
			$order->save();
			
			$process['order_id']     = $data['order_id'];
			
			$process['order_status'] = $order_status;
			$process['remark']       = '确认接单';
			$flag = OrderProcess::create($process);	

			
			

			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			Log::info('确认订单发生异常'.$e->getMessage());
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		//dd($order);
		if($flag) {
			$rs['status'] = true;
			$rs['msg']    ='操作成功';
			return $rs;
		}
		return $rs;
		

	}

	/**
	 * 发货
	 */
	public static function send($data)
	{
		$rs['status']   = false;
		$rs['msg']      = '操作失败';
		$data['status'] = 4;
		$data['dispatched_at'] = date('Y-m-d H:i:s');
	   
		DB::beginTransaction();
		try{
			$order = Order::find($data['id']);
			Order::where(['id'=>$data['id']])->update($data);
			$process['order_id']     = $data['id'];
			
			$process['order_status'] = $data['status'];
			$process['remark']       = '已填写快递信息';
			$flag = OrderProcess::create($process);	

			
			

			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			Log::info('确认订单发生异常'.$e->getMessage());
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		//dd($order);
		if($flag) {
			$rs['status'] = true;
			$rs['msg']    ='操作成功';


			$msg    = $order->toArray();
			$msg['product_info'] = OrderRepo::productInfo($order->id);
			$msg['openid'] = $order->user->small_openid;
			WechatTpl::sendTplMsg('send',$msg); 
			return $rs;
		}
		return $rs;
		

	}

	

	/**
	 * 开始配送
	 */
	public static function dispatch($data)
	{
		$rs['status'] = false;
		$order_status = 5;
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);
			if(empty($order->address_id)) {
				$rs['msg'] = '此订单是自取订单无需配送';
				return $rs;
			}
			//配送订单确认后要上传图才能继续
			// if($order->status!=4){
			// 	$rs['msg'] = '请先上传订单商品图片';
			// 	return $rs;
			// }

			$order->dispatched_at = date('Y-m-d H:i:s');
			$order->status = $order_status;
			$order->save();
			$process['order_id']     = $data['order_id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家已配送';
			$flag = OrderProcess::create($process);	
			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		if($flag) {
			$rs['status'] = true;
			return $rs;
		}
		return $rs;
		

	}

	/**
	 * 从待付款中付款
	 */
	public static function pay($data)
	{
		$rs['status'] = false;
		$order = Order::where(['code'=>$data['code']])->first();
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}

		if($order->status !=1 ){
			$rs['msg'] = '订单状态错误'; 
			return $rs;
		}	

		if($data['total_money'] != $order->total_money) {
			$rs['msg'] = '订单金额错误';
			return $rs;
		}
		$rs['status'] = true;
		$rs['data'] = self::wechatUnifyOrder($data);
		return $rs;

	}

	public static function count($where)
	{
		$user_id   = $where['user_id'];
		$key       = $where['key'];
		//$redis_key = 'fruit:users:order:count:'.$user_id.'_'.$key;
		//$num = RedisService::get($redis_key);
		//if($num) return $num;

		$num    = Order::where(['user_id'=>$user_id])
						->whereIn('status',$where['status'])
						->count();
		//$redis_key = 'fruit:users:order:count:'.$user_id.'_'.$key;
		//$redis_data = (int)$num;				
		//RedisService::set($redis_key,$redis_data);
		return $num;
	}


	public static function cancle($data)
	{
		$rs['status'] = false;
		$where['code'] = $data['code'];	
		$order = Order::where($where)->first();
		$order_status = $order->status;
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}
		// if($order->status !=1 ){
		// 	$rs['msg'] = '订单状态不允许取消'; 
		// 	return $rs;
		// }
		DB::beginTransaction();
		try {
			if($order_status==1 || $order_status==2) {
				// 待确认订单不需要审核
				$order->status = '-1';	
			} else {
				// 其他状态需要 卖家审核
				$order->status = '-3';
			}
			
			$order->save();
			// 恢复优惠券
			if($order->user_coupon_id){
				UserCouponRepo::update(['id'=>$order->user_coupon_id],['is_used'=>0]);
			}

			if($order->user_money) {
				$money['type']    = 4;
				$money['shop_id'] = $order->shop_id;
				$money['user_id'] = $order->user_id;
				$money['money']   = $order->user_money;
				UserMoneyLogRepo::create($money);
			}

			// 如果已经支付 那么要退款
			Log::info('用户自己取消未确认的订单：'.$order_status.'----'.$order->transaction_id);
			

			// 要推送老板端
			if($order->status == '-3') {
				$suWhere['shop_id'] = $order->shop_id;
				$suWhere['role_id'] = 100;
				$shopUser = ShopUserRepo::find($suWhere);
				if(object_get($shopUser,'boss_form_id')) {
					$msg = $order->toArray();
					$msg = array_only($msg,['code','created_at','address']);
					$msg['user_name']    = object_get($order,'user.nickname');
					// 查找店老板
					
					$msg['openid']       = object_get($shopUser,'openid'); 
					$msg['form_id']      = object_get($shopUser,'boss_form_id');
					$msg['product_info'] = self::productInfo($order->id);		
					Log::info($order->shop_id.'老板端订单取消提醒:'.json_encode($msg));
					WechatTpl::sendTplMsg('shop_order_cancle',$msg,2);	
				}
					
			}

			
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			Log::info('取消订单失败：'.$e->getMessage());
			return $rs;
		}
		
		$rs['status'] = true;
		return $rs;	
	}

	
	public static function wechatUnifyOrder($data)
	{
		$payment = EasyWeChat::payment(); // 微信支付
		$result = $payment->order->unify([
		    'body'         => '幸福壹选订单',
		    'out_trade_no' => $data['code'],
		    'trade_type'   => 'JSAPI',  // 必须为JSAPI
		    'openid'       => $data['openid'], // 这里的openid为付款人的openid
		    'total_fee'    => $data['total_money'], // 总价单位分
		    'timeStamp' => time(),
		    'notify_url' => config('app.url').'/wechat/pay-notify',
		]);

		// 如果成功生成统一下单的订单，那么进行二次签名
		if ($result['return_code'] === 'SUCCESS') {
		    // 二次签名的参数必须与下面相同
		    $params = [
		        'appId'     => config('wechat.mini_program.default.app_id'),
		        'timeStamp' => time(),
		        'nonceStr'  => $result['nonce_str'],
		        'package'   => 'prepay_id=' . $result['prepay_id'],
		        'signType'  => 'MD5',
		    ];
		    // config('wechat.payment.default.key')为商户的key
		    $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
		    $params['signJs'] = $result['sign'];
		    $params['order_id']      = $data['order_id'];
		    $params['order_code']    = $data['code'];
		    $params['order_created'] = date('Y-m-d H:i:s');
		    return $params;
		} else {
			$rs['param'] = $data;
			$rs['result'] = $result;
		    return $rs;
		}
	}

	


	
	public static function total($where)
	{
		$today =  Order::where($where)->whereDate('created_at', '=', date('Y-m-d'))->sum('total_money');
		$all = Order::where($where)->sum('total_money');
		$data['today'] = $today;
		$data['all'] = $all;
		return $data;
	}

	public static function reject($data)
	{
		$rs['status'] = false;
		$order_status = '-2';
		$where['id'] = $data['order_id'];
		$order = Order::where($where)->first();

		if(empty($order)) {
			$rs['msg'] = '订单不存在';
			return $rs;
		}		

		$order->status = $order_status;
		$flag = $order->save();
		if($flag) {
			$rs['status'] = true;
			$process['order_id']     = $data['order_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家拒绝接单';
			$flag = OrderProcess::create($process);	
			return $rs;
		}
		$rs['msg'] = '拒单失败';
		return $rs;
	}

	

	



	public static function comment($data)
	{
		$rs['status'] = false;
		$rs['msg'] = '评价失败';
		$where['order_id'] = array_pull($data,'order_id');
		$where['user_id']  = $data['user_id'];
		DB::beginTransaction();
		try {
			$order = Order::where($where)->first();
			if(!$order) {
				$rs['msg'] = '订单不存在';
				return $rs;
			}

			if($order->status!=100) {
				$rs['msg'] = '完成后的订单才能评价';
			}
			$order->status = 200;
			$order->save();

			$op['order_id'] = $order->id;
			$op['user_id'] 	= $data['user_id'];				
			$op['point']    = $data['point'][$k];
			$op['remark']   = $data['remark'];
			$flag = OrderPoint::create($op);
			
			
			if($flag) {
				DB::commit();
				$rs['status'] = true;
				return $rs;
			}
			DB::rollBack();
			return $rs;
			
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		return $rs;
	} 

	public static function orderCount()
	{
		$num = Order::where('status','!=','1')->count();
		return $num;
	}

	public static function orderAmount()
	{
		$total = Order::where('status','!=','1')->sum('total_price');
		return $total/100;	
	}

	// 退款
	public static function refund($data)
	{
		$rs['status'] = false;
		$order = Order::find($data['id']);
		if($order) {			
			$or['order_id'] = $data['id'];
			$or['remark']   = $data['remark'];
			$or['user_id']  = $order->user_id;
			$flag = OrderRefund::create($or);
			if($flag){
				$order->status = '-100';
				$order->save();
				$rs['status']  = true;

				// 推送模板消息
				$msg    = $order->toArray();
				$msg['remark'] = $data['remark'];
				$msg['openid'] = $order->user->small_openid;
				WechatTpl::sendTplMsg('refund',$msg);
				return $rs;	
			} 
		} else {
			$rs['msg'] = '订单不存在';
		}
		return $rs;
	}

	public static function productInfo($order_id)
	{
		$products_names = '';
		$products = OrderProduct::where(['order_id'=>$order_id])
						->pluck('product_name');
		if($products) {
			$pros = $products->toArray();
			$products_names = implode(',', $pros);
			return $products_names;
		}

		return $product_names;				


	}

	

	public static function getStatus()
	{
		$order = new Order;
		return $order->status_arr;
	}


	// 超过24小时自动收货
	public static function autoRecived()
	{   
		$where['status'] = 5;
		$orders = Order::where($where)->get();
		DB::beginTransaction();
		try {
			$day = date("Y-m-d H:i:s", strtotime( '-1 days' ) );
			foreach ($orders as $k => $order) {
				
				if($order->dispatched_at<=$day) {
					$od['completed_at'] = date('Y-m-d H:i:s');
					$od['status']       = 100;
					Order::where(['id'=>$order->id])->update($od);
				
					

					

					$process['order_id']     = $order->id;
					$process['order_status'] = 100;
					$process['remark']       = '发货超过72小时订单自动完成';
					$flag = OrderProcess::create($process);
					$rs['status'] = true;	
				}			
			}
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
		}
	}


	public static function complete($data)
	{
		$rs['status'] = false;
		$order_status = '100';
		$where['id'] = $data['order_id'];
		$order = Order::where($where)->first();

		if(empty($order)) {
			$rs['msg'] = '订单不存在';
			return $rs;
		}		

		$order->status       = $order_status;
		$order->completed_at = date('Y-m-d H:i:s');
		$flag = $order->save();
		if($flag) {
			$rs['status'] = true;
			$process['order_id']     = $data['order_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '订单已完成';
			$flag = OrderProcess::create($process);	
			return $rs;
		}
		$rs['msg'] = '操作失败';
		return $rs;
	}

	public static function getOrderList($userId)
    {
        //全部订单
        return Order::where('user_id',$userId)->with('products')->orderBy('id','desc')
            ->paginate(20);
    }


	

	

	
	
	

	
	
	
}